#pragma once
#include <iostream>
#include <memory>
#include <sys/epoll.h>
#include "Connection.hpp"
#include "Socket.hpp"
#include "Channel.hpp"
#include "Util.hpp"

class Listener : public Connection
{
public:
    Listener(uint16_t port) : _listensockfd(std::make_unique<TcpSocket>()), _port(port)
    {
        _listensockfd->BuildListenSocketMethod(_port);
        SetSockfd(_listensockfd->GetSockFd());
        SetEvent(EPOLLIN | EPOLLET);   //  写 是常设置的
    }
    void Recver() override
    {
        // 获取新链接
        while (true) // ET模式 非阻塞循坏获取新连接
        {
            InetAddr clientaddr;
            int error = 0;
            int sockfd = _listensockfd->Accept(&clientaddr, &error);
            if (sockfd < 0)
            {
                if (error == EAGAIN)
                {
                    break;
                }
                else if (error == EINTR)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
            // 获取新连接成功
            // 设为非阻塞
            SetNonBlock(sockfd);
            // 1.构建新的连接
            std::shared_ptr<Connection> conn = std::make_shared<Channel>(sockfd, clientaddr);
            // 设置解析回调
            conn->SetCallBack(_cb);

            // 2.添加到reactor
            Owner()->AddConnection(conn);

        }
    }
    void Sender() override
    {
        // empty
    }
    void Excepter() override
    {
        // empty
    }
    ~Listener()
    {
    }

private:
    std::unique_ptr<Socket> _listensockfd;
    uint16_t _port;
};